package JDBCUTILS;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.Properties;

public class JDBCUtils {
    private static String password;
    private static  String url;
    private static  String username;

    static {
        InputStream inputStream=
                JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
        Properties p =new Properties();
        try {
            p.load(inputStream);
            url=p.getProperty("url");
            username=p.getProperty("username");
            password=p.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        DataSource dataSource=new MysqlDataSource() ;
        ((MysqlDataSource)dataSource).setPassword(password);
        ((MysqlDataSource)dataSource).setUser(username);
        ((MysqlDataSource)dataSource).setUrl(url);
        try {
            System.out.println("数据库连接成功");
            return dataSource.getConnection();
        } catch (SQLException e) {
            System.out.println("数据库连接失败");
            e.printStackTrace();
        }
        return null;
    }
    public  static void close(Connection conn,ResultSet resultSet,PreparedStatement preparedStatement){
            try {
                if(resultSet!=null) {
                    resultSet.close();
                    resultSet=null;
                }
                if(conn!=null){
                    conn.close();
                    conn=null;
                }
                if(preparedStatement!=null){
                    preparedStatement.close();
                    preparedStatement=null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

    }
}
